#!/bin/bash -eu
#
# Copyright 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

readonly jenkins_user="admin"
readonly jenkins_password="$(get_attribute_value "jenkins-admin-password")"

# Generates a password salted hashed with bcrypt
readonly hash="#jbcrypt:$(htpasswd -bnBC 10 "" "${jenkins_password}" \
                          | tr -d ':\n' \
                          | sed 's/$2y/$2a/')"

readonly token=$(dd if=/dev/urandom bs=72 count=1 2>/dev/null | base64 - | tr -d \\n)

systemctl stop jenkins

rm -f /var/lib/jenkins/secrets/initialAdminPassword
rm -rf /var/lib/jenkins/users/admin*
rm -rf /var/lib/jenkins/users/*

mkdir -p "/var/lib/jenkins/users/${jenkins_user}"

cat <<EOF >/var/lib/jenkins/users/${jenkins_user}/config.xml
<?xml version='1.0' encoding='UTF-8'?>
<user>
  <fullName>admin</fullName>
  <properties>
    <jenkins.security.ApiTokenProperty>
      <apiToken>${token}</apiToken>
    </jenkins.security.ApiTokenProperty>
    <hudson.model.MyViewsProperty>
      <views>
        <hudson.model.AllView>
          <owner class="hudson.model.MyViewsProperty" reference="../../.."/>
          <name>all</name>
          <filterExecutors>false</filterExecutors>
          <filterQueue>false</filterQueue>
          <properties class="hudson.model.View\$PropertyList"/>
        </hudson.model.AllView>
      </views>
    </hudson.model.MyViewsProperty>
    <hudson.model.PaneStatusProperties>
      <collapsed/>
    </hudson.model.PaneStatusProperties>
    <hudson.search.UserSearchProperty>
      <insensitiveSearch>false</insensitiveSearch>
    </hudson.search.UserSearchProperty>
    <hudson.security.HudsonPrivateSecurityRealm_-Details>
      <passwordHash>${hash}</passwordHash>
    </hudson.security.HudsonPrivateSecurityRealm_-Details>
  </properties>

EOF
chown -R jenkins:jenkins "/var/lib/jenkins/users/${jenkins_user}"

systemctl start jenkins
